/**
 * 单一列类型的通用操作函数
 */
import models from 'src-ssr/db/sequelize';
import moment from 'moment';
import * as tools from 'src-ssr/util/common';
import logs from 'src-ssr/util/logs';
import TableHelper from 'src-ssr/db/tableHelper';

/**
 * 取已删除模块
 * @param {*} modelName 模块名
 * @param {*} modelLabel 模块名称
 * @param {*} menuName 菜单名
 * @param {*} req 前端请求
 * @returns
 */
/* export const getRecycleData = async (modelName, modelLabel, menuName, req) => {
  const { startRow, count, filter, sortBy, descending } = req.body;
  let ret = { rows: [], count: 0 };
  try {
    ret = await models.recycle.findAndCountAll({
      attributes: ['data', ['create_time', 'delete_time'], ['create_user_name', 'delete_user_name']],
      where: { module: menuName },
      order: [['id', 'desc']],
      offset: startRow,
      limit: count,
      raw: true
    });
  } catch (e) {
    console.error(modelLabel + '回收列表出错', e);
  }

  const rows = ret.rows.map(row => {
    const { data, delete_time, delete_user_name } = row;
    return {
      ...data,
      delete_time,
      delete_date: moment(delete_time, 'X').format('YYYY/MM/DD HH:mm'),
      delete_user_name
    }
  });

  return {
    data: rows,
    rowsNumber: ret.count
  };
}; */

// 新增数据
export const createData = async (modelName, modelLabel, menuName, req, isTenant = false, checkRight = ['func', 'add']) => {
  const { formData } = req.body;
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  if (checkRight && checkRight.length > 0) {
    const right = await tools.checkUserRight(user, menuName, checkRight);

    if (!right.and) {
      return { result: 'fail', message: `没有新增${modelLabel}权限` };
    }
  }

  const data = TableHelper.filterField(modelName, formData);
  data.create_user_id = user.id;
  data.create_user_name = user.nickname;

  if (isTenant) data.tenant_id = user.tid; // 是否为租户数据

  let newModel = {};
  try {
    newModel = await models[modelName].create(data);

    newModel = await models[modelName].findByPk(newModel.id);
    newModel = newModel.toJSON();
  } catch (e) {
    console.error('新增' + modelLabel + '出错', e);
  }

  logs.recordLogs(user, { type: 'add', model: modelLabel, content: { formData } }, req);
  return { result: 'ok', id: newModel.id, uid: newModel.uid && tools.binToUuid(newModel.uid) };
};

// 更新数据
export const updateData = async (modelName, modelLabel, menuName, req, isTenant = false, checkRight = ['func', 'edit']) => {
  const { id, formData } = req.body;
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  if (checkRight && checkRight.length > 0) {
    const right = await tools.checkUserRight(user, menuName, checkRight);

    const oriData = await models[modelName].findByPk(id);
    if (user.id != oriData.create_user_id && !right.edit) {
      return { result: 'fail', message: `没有修改${modelLabel}权限` };
    }
  }

  const data = TableHelper.filterField(modelName, formData);
  data.modify_user_id = user.id;
  data.modify_user_name = user.nickname;

  try {
    const rawData = await models[modelName].findByPk(id);

    if (isTenant && rawData.tenant_id != user.tid) {
      return { result: 'fail', message: '用户与数据非同一组织不能修改' };
    }

    for (const key in data) {
      rawData[key] = data[key];
    }
    await rawData.save();
    // await models[modelName].update(data, { where: { id } });
  } catch (e) {
    console.error('修改' + modelLabel + '出错', e);
  }

  logs.recordLogs(user, { type: 'edit', model: modelLabel, content: { formData } }, req);
  return { result: 'ok' };
};

// 删除数据
export const destroyData = async (modelName, modelLabel, menuName, req, isTenant = false, checkRight = ['func', 'edit']) => {
  const { id } = req.body;
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  const data = await models[modelName].findByPk(id);
  if (checkRight && checkRight.length > 0) {
    const right = await tools.checkUserRight(user, menuName, checkRight);

    if (user.id != data.create_user_id && !right.edit) {
      return { result: 'fail', message: `没有删除${modelLabel}权限` };
    }
  }

  if (isTenant && data.tenant_id != user.tid) {
    return { result: 'fail', message: '用户与数据非同一组织不能删除' };
  }

  logs.recordLogs(user, { type: 'delete', model: modelLabel, content: data }, req);

  try {
    await data.destroy();
    // 放入回收站
    // await models.m_recycle.create({
    //   module: menuName,
    //   data,
    //   create_time: moment().format('X'),
    //   create_user_id: user.id,
    //   create_user_name: user.nickname
    // });
  } catch (e) {
    console.error('删除' + modelLabel + '出错', e);
  }

  return { result: 'ok' };
};
